package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 保存套餐到 setmeal 表，同时将关联的菜品添加到关联的 setmeal_dish 表
     * @param setmealDto 所有套餐相关的信息
     */
    @Transactional  // 添加事务
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        // 1.将套餐的相关信息添加到 setmeal 表
        this.save(setmealDto);

        // 2.将该套餐相关的菜品添加到 setmeal_dish 表
        // 2-1 所有相关的菜品
        List<SetmealDish> dishes = setmealDto.getSetmealDishes();
        // 2-2 给菜品添加套餐的id(关系绑定)
        dishes.stream().map((item) -> {
           item.setSetmealId(setmealDto.getId());
           return item;
        }).collect(Collectors.toList());
        // 2-3 将数据添加到 setmeal_dish 表
        setmealDishService.saveBatch(dishes);
    }
}
